<template>
  <div class="w1 h1 main_content">
    <div class="search-content">
      <Col class="panel search-panel"
        :span="24">
      <Form :model="formHeader"
        :label-width="80"
        inline>
        <FormItem label="设备名称："
          v-if="userRole!='ROLE_DEMO'">
          <Select v-model="formHeader.deviceId"
            style="width:200px"
            @on-change="handlDeviceChange">
            <Option v-for="(item,index) in deviceList"
              :value="item.id"
              :key="index"
              :label="item.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="设备名称："
          v-if="userRole=='ROLE_DEMO'">
          <Select v-model="formHeader.deviceId"
            style="width:200px"
            @on-change="handlDeviceChange">
            <Option v-for="(item,index) in deviceList"
              :value="item.id"
              :key="index"
              :label="!!item.alias?item.alias:item.name"></Option>
          </Select>
        </FormItem>
        <FormItem label="参数名称：">
          <Select v-model="formHeader.dataType"
            style="width:200px"
            @on-change="triggerAliasChange">
            <Option v-for="(item,index) in deviceAlias"
              :value="item.id"
              :key="index"
              :label="item.channelAlias"></Option>
          </Select>
        </FormItem>
        <FormItem label="查询时间：">
          <DatePicker :clearable="false"
            type="daterange"
            :options="timeOptions"
            format="yyyy/MM/dd"
            v-model="formHeader.timeRange"
            placement="right-start"
            placeholder="请选择日期"
            @on-change="handleDateChange"
            style="width:200px"></DatePicker>
        </FormItem>
        <FormItem class="margin-left-20">
          <Button type="primary"
            @click="_requireThing">查询</Button>
          <Button v-if="showChartBtn"
            type="primary"
            @click.native="viewChart"
            style="margin-left:10px;">查看曲线</Button>
        </FormItem>
      </Form>
      <span style="margin-left:10px;color:#c0c0c0;font-size:12px;">注：可查询三年的历史数据，仅显示三个月的参数数据曲线</span>
      </Col>
    </div>
    <div class="scroll__content uhistory_content">
      <Row class="scroll-content__row">
        <!-- 表格 -->
        <Col class="panel table-panel"
          :span="24">
        <Table :columns="columns"
          :data="tableData"
          border
          :loading="pageInfo.loading"></Table>
        </Col>
        <!-- 分页 -->
        <Col class="panel page-panel cf"
          :span="24"
          style="margin-bottom:40px;">
        <div class='page-title'>
          <p>显示
            <span>{{startTime?moment(startTime).format('YYYY-MM-DD'):""}}</span>-
            <span>{{endTime?moment(endTime).format('YYYY-MM-DD'):""}}</span>数据，共<span>{{total}}</span>条
          </p>
        </div>
        <Page :total="pageInfo.total"
          show-total
          :page-size="15"
          class="fr"
          :current.sync="pageInfo.page"
          @on-change="switchThePaging"></Page>
        </Col>
        <Col :span="24"
          class="page-bottom">
        </Col>
        <!-- 查看曲线 -->
        <Modal v-model="dialogVisable"
          width="70%"
          footer-hide>
          <div style="height: 400px;padding:5px;">
            <hisChart :mapData="mapData"
              :deviceAlias="deviceAlias"
              v-if="dialogVisable"
              :current="formHeader.dataType"
              :currentName="currentName"></hisChart>
          </div>
        </Modal>
      </Row>
    </div>
  </div>
</template>
<script>
import { getDeviceListOfNew, getDeviceAliasList, getHistoryList } from '@/api'
import deviceParams from './deviceParams'
import hisChart from '@/components/history/his-chart'
import PermissionMixin from '../PermissionMixin'
export default {
  mixins: [PermissionMixin],
  components: { hisChart },
  mounted() {
    this._getDeviceList()
  },
  data() {
    return {
      params: {
        companyId: ''
      },
      showChartBtn: false,
      timeOptions: {
        disabledDate(date) {
          return date && date.valueOf() > Date.now()
        }
      },
      formHeader: {
        deviceId: '',
        dataType: '',
        timeRange: [
          this.moment()
            .add(-3, 'days')
            .format(),
          this.moment()
            .add(-1, 'days')
            .format()
        ]
      },
      currentName: '',
      mapData: {},
      deviceList: [],
      deviceAlias: [],
      dialogVisable: false,
      tableData: [],
      pageInfo: {
        page: 1,
        total: 0,
        loading: false
      },
      columns: [
        {
          title: '序号',
          type: 'index',
          align: 'center'
        },
        {
          title: '所属区域',
          key: 'groupName',
          align: 'center'
        },
        {
          title: '参数名称',
          key: 'des',
          align: 'center'
        },
        {
          title: '参数值',
          align: 'center',
          render: (h, params) => {
            const type = params.row.type,
              value = params.row.value,
              unit = params.row.unit
            if (type >= 53 && type <= 55 && value == 0) {
              return h('span', '-')
            } else {
              return h('span', value + unit)
            }
          }
        },
        {
          title: '采集时间',
          align: 'center',
          render: (h, params) => {
            const time = params.row.createdAt
            return h('span', this.filterTime(time))
          }
        }
      ],
      deviceAlias: [],
      selectDeviceId: '',
      startTime: '',
      endTime: '',
      total: 0,
      aliasCanShowBtn: false,
      dateCanShowBtn: true
    }
  },
  methods: {
    // 设备列表
    _getDeviceList() {
      const vm = this
      const companyId = vm.companyId
      getDeviceListOfNew({
        companyId,
        size: 1000
      }).then(res => {
        if (res.code == 200) {
          vm.deviceList = res.data.list
          vm.formHeader.deviceId = res.data.list[0].id
          vm._getHistoryList()
          vm.handlDeviceChange(vm.formHeader.deviceId)
        }
      })
    },

    triggerAliasChange(value) {
      const vm = this
      if (value) {
        vm.currentName = vm.deviceAlias.find(t => t.id === value).channelAlias
        if (vm.selectDeviceId.startsWith('9')) {
          vm.aliasCanShowBtn = true
        } else {
          if (vm.formHeader.deviceId) {
            if (vm.formHeader.dataType >= 5 && vm.formHeader.dataType <= 15) {
              vm.aliasCanShowBtn = true
            } else if (vm.formHeader.dataType === 63) {
              vm.aliasCanShowBtn = true
            } else {
              vm.aliasCanShowBtn = false
            }
          } else {
            vm.aliasCanShowBtn = false
          }
        }
      } else {
        vm.aliasCanShowBtn = false
      }
      if (vm.dateCanShowBtn && vm.aliasCanShowBtn) {
        vm.showChartBtn = true
      } else {
        vm.showChartBtn = false
      }
    },

    filterTime(time) {
      return this.moment(time).format('YYYY-MM-DD HH:mm:ss')
    },

    switchThePaging(index) {
      this.pageInfo.page = index
      this._getHistoryList()
    },

    _requireThing() {
      let vm = this
      vm.pageInfo.page = 1
      vm._getHistoryList()
    },

    _getHistoryList() {
      const vm = this
      vm.pageInfo.loading = true
      let time = vm.formHeader.timeRange
      let timeRangeStart = vm.moment(time[0]).valueOf()
      let timeRangeEnd = vm.moment(time[1]).valueOf()
      if (timeRangeStart === timeRangeEnd) {
        let today = this.moment(
          new Date(new Date().setHours(0, 0, 0, 0))
        ).valueOf()
        if (timeRangeStart === today) {
          timeRangeEnd = this.moment().valueOf()
        } else {
          timeRangeEnd = timeRangeStart + 86399999
        }
      } else {
        timeRangeEnd = timeRangeEnd + 86399999
      }

      const params = {
        page: vm.pageInfo.page,
        size: 15,
        deviceId: vm.formHeader.deviceId,
        type: vm.formHeader.dataType,
        timeRangeStart,
        timeRangeEnd
      }
      getHistoryList(params).then(res => {
        if (res.code == 200) {
          vm.total = res.data.total
          vm.startTime = res.data.timeRange[0]
          vm.endTime = res.data.timeRange[1]
          vm.tableData = res.data.data
          vm.pageInfo.total = res.data.total
          setTimeout(() => {
            vm.pageInfo.loading = false
          }, 500)
        }
      })
    },

    // 设备更改
    handlDeviceChange(id) {
      this.formHeader.dataType = ''
      this.deviceAlias = []
      if (!!id) {
        this.formHeader.deviceId = id
        this._getDeviceAliasList()
      } else {
        this.showChartBtn = false
      }
    },

    // 获取设备参数列表
    _getDeviceAliasList() {
      const vm = this
      const value = vm.formHeader.deviceId || ''
      const selectedDeviceId = vm.deviceList.find(t => t.id === value).deviceId
      vm.selectDeviceId = selectedDeviceId
      if (selectedDeviceId.startsWith('9')) {
        const params = { deviceId: selectedDeviceId }
        getDeviceAliasList(params).then(res => {
          if (res.code == 200) {
            this.deviceAlias = [...res.data]
          } else {
            this.deviceAlias = []
          }
        })
      } else {
        this.deviceAlias = [...deviceParams]
      }
    },

    // 查看曲线
    viewChart() {
      const _t = this
      _t.dialogVisable = true
      let time = [..._t.formHeader.timeRange]

      let timeRangeStart = _t.moment(time[0]).valueOf(),
        timeRangeEnd = _t.moment(time[1]).valueOf() + 86399999
      let params = {
        deviceId: _t.formHeader.deviceId,
        dataType: _t.formHeader.dataType,
        timeRangeStart,
        timeRangeEnd
      }
      this.mapData = params
    },

    // 时间选择器chagne
    handleDateChange() {
      const vm = this
      const timeRange = vm.formHeader.timeRange
      if (Array.isArray(timeRange) && timeRange.length === 2) {
        const start = vm.moment(timeRange[0])
        const end = vm.moment(timeRange[1])
        const diff = end.diff(start, 'month')
        if (diff > 2) {
          vm.dateCanShowBtn = false
        } else {
          vm.dateCanShowBtn = true
        }
      }

      if (vm.dateCanShowBtn && vm.aliasCanShowBtn) {
        vm.showChartBtn = true
      } else {
        vm.showChartBtn = false
      }
    }
  }
}
</script>
